package com.qcby.community.controller;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qcby.community.annotation.LogAnnotation;
import com.qcby.community.entity.User;
import com.qcby.community.entity.UserRole;
import com.qcby.community.form.LoginForm;
import com.qcby.community.form.UpdatePasswordForm;
import com.qcby.community.form.UserAddOrUpdateForm;
import com.qcby.community.form.UserForm;
import com.qcby.community.mapper.RoleMapper;
import com.qcby.community.service.MenuService;
import com.qcby.community.service.UserRoleService;
import com.qcby.community.service.UserService;
import com.qcby.community.util.Result;
import com.qcby.community.vo.MenuRouterVO;
import com.qcby.community.vo.PageVO;
import com.qcby.community.vo.UserEditVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-03-23
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 通过登录的用户来决定动态路由的加载
     * 显示该用户的权限能访问的菜单
     * @param session
     * @return
     */
    @GetMapping("/getRouters")
    public Result getRouters(HttpSession session){
        //1.展示获取该用户的所有基本信息
        User user = (User) session.getAttribute("user");
        //2.获取该用户所对应的权限角色名称
        String role = this.roleMapper.getRoleNameByUserId(user.getUserId());
        //3.获取该角色所对应的所有权限菜单并进行合理封装返回
        List<MenuRouterVO> routers= menuService.getMenuRouterByUserId(user.getUserId());
        return Result.ok()
                .put("data", user)
                .put("roles", role)
                .put("routers", routers);
    }

    /**
     * 修改密码
     * @param updatePasswordForm
     * @param session
     * @return
     */
    @LogAnnotation("修改密码")
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody UpdatePasswordForm updatePasswordForm,HttpSession session) {
        //获取到session中用户，目的：获取原密码
        User user = (User) session.getAttribute("user");
        //验证原密码是否正确，输入的原密码加密
        String password = SecureUtil.sha256(updatePasswordForm.getPassword());
        if (!user.getPassword().equals(password)) {
            return Result.ok().put("status", "passwordError");
        }
        //更新密码
        String newPassword = SecureUtil.sha256(updatePasswordForm.getNewPassword());
        user.setPassword(newPassword);
        boolean updateById = this.userService.updateById(user);
        if (updateById) {
            return Result.ok().put("status", "success");
        }
        return Result.error("更新密码失败");
    }

    /**
     * 分页查询
     * @param userForm
     * @return
     */
    @RequestMapping("/list")
    public Result list(UserForm userForm){
        PageVO pageVO = this.userService.userList(userForm);
        return Result.ok().put("data",pageVO);
    }

    /**
     * 添加
     * @param userAddOrUpdateForm
     * @return
     */
    @LogAnnotation("添加用户")
    @PostMapping("/add")
    public Result add(@RequestBody UserAddOrUpdateForm userAddOrUpdateForm){
        User user = new User();
        BeanUtils.copyProperties(userAddOrUpdateForm, user);
        String password1 = SecureUtil.sha256(user.getPassword());
        user.setPassword(password1);
        boolean save = this.userService.save(user);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(userAddOrUpdateForm.getRoleId());
        boolean save1 = this.userRoleService.save(userRole);
        if(save && save1){
            return Result.ok();
        }
        return Result.error("添加用户失败");
    }

    /**
     * 通过id查询
     * @param id
     * @return
     */
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Integer id){
        User user = this.userService.getById(id);
        UserEditVO userEditVO = new UserEditVO();
        BeanUtils.copyProperties(user,userEditVO);
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id",id);
        UserRole userRole = this.userRoleService.getOne(userRoleQueryWrapper);
        userEditVO.setRoleId(userRole.getRoleId());
        return Result.ok().put("data",userEditVO);
    }

    /**
     * 修改
     * @param userEditVO
     * @return
     */
    @LogAnnotation("编辑用户")
    @PutMapping("/edit")
    public Result edit(@RequestBody UserEditVO userEditVO){
        User user = new User();
        BeanUtils.copyProperties(userEditVO, user);
        String password1 = SecureUtil.sha256(user.getPassword());
        user.setPassword(password1);
        boolean updateById = this.userService.updateById(user);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(userEditVO.getRoleId());
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getUserId());
        this.userRoleService.update(userRole, queryWrapper);
        if(updateById) return Result.ok();
        return Result.error("编辑用户失败");
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @LogAnnotation("删除用户")
    @DeleteMapping("/del")
    public Result del(@RequestBody Integer[] ids){
        boolean removeByIds = this.userService.removeByIds(Arrays.asList(ids));
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(ids.length > 0, "user_id", ids);
        boolean remove = this.userRoleService.remove(queryWrapper);
        if(removeByIds && remove) {
            return Result.ok();
        }
        return Result.error("删除用户失败");
    }



}

